package com.frxuexi.park2305.news

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.NewsBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.GlideUtils
import com.frxuexi.park2305.R
import com.frxuexi.park2305.databinding.ActivityNewsAddBinding
import com.frxuexi.repair.adapter.RepairImgAdapter
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/NewsAddActivity")
@AndroidEntryPoint
class NewsAddActivity : BaseActivity<ActivityNewsAddBinding, NewsIntent, NewsViewModel>() {
    override val binding: ActivityNewsAddBinding by lazy {
        ActivityNewsAddBinding.inflate(
            layoutInflater
        )
    }
    override val vm: NewsViewModel by viewModels<NewsViewModel>()
    val repairImgAdapter by lazy { RepairImgAdapter() }
    val imgs = mutableListOf<String>()

    @JvmField
    @Autowired
    var id: Int? = -1

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.UPLOAD -> {
                                ToastUtils.showLong("上传成功")
                                val s = it.data as String
                                val fname = s.split(":")[1]
                                val path = "http://10.161.9.80:2209/images/news/${
                                    SPUtils.getInstance().getInt(
                                        Const.UID, -1
                                    )
                                }/${fname}"
                                imgs.add(path)
                                repairImgAdapter.addData(path)
                                repairImgAdapter.notifyDataSetChanged()
                            }

                            RequestType.ADD -> {
                                ToastUtils.showLong("发表成功")
                                finish()
                            }
                            RequestType.UPDATE->{
                                ToastUtils.showLong("修改成功")
                                finish()
                            }

                            else -> {
                                val item = it.data as NewsBeanItem
                                binding.bean = item
                                imgs.addAll(item.images)
                                repairImgAdapter.addData(item.images)
                                repairImgAdapter.notifyDataSetChanged()

                            }
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)

        if (id != -1) {
            vm.sendIntent(NewsIntent.getNewsById(id!!))
        }

        binding.newsAddRv.apply {
            adapter = repairImgAdapter
            layoutManager = GridLayoutManager(this@NewsAddActivity, 3)
        }
        binding.newsaddIv.setOnClickListener {
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }

        repairImgAdapter.addChildClickViewIds(com.frxuexi.repair.R.id.img_delete)
        repairImgAdapter.setOnItemChildClickListener { adapter, view, position ->
            imgs.removeAt(position)
            repairImgAdapter.data.removeAt(position)
            repairImgAdapter.notifyItemRemoved(position)
        }

        binding.newsaddTitle.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val length = s?.length
                binding.newsaddNum.setText("${length}/50")
                if (length == 50) {
                    binding.newsaddNum.setTextColor(getColor(com.frxuexi.lib_base.R.color.redfont))
                } else {
                    binding.newsaddNum.setTextColor(getColor(com.frxuexi.lib_base.R.color.darkgray))
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.newaddIvdate.setOnClickListener {
            showDateDialog {
                binding.newsaddDate.setText(it)
            }
        }

        binding.newsaddUser.setText(SPUtils.getInstance().getString(Const.UNAME))

        binding.headAdd.setOnClickListener {
            val title = binding.newsaddTitle.text.toString()
            val content = binding.newsaddContent.text.toString()
            val date = binding.newsaddDate.text.toString()
            val type = binding.newsaddType.text.toString()
            val user = binding.newsaddUser.text.toString()
            val item =
                NewsBeanItem(true, content, null, imgs, date, true, user, title, type, 0)
            if (id != -1) {
                item.id=id
                vm.sendIntent(NewsIntent.updateNews(id!!,item))
            }else {
                vm.sendIntent(NewsIntent.addNews(item))
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            val bean =
                data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)
            val path = bean!!.path
            val split = path.split("/")
            val name = split.get(split.lastIndex)
            vm.sendIntent(NewsIntent.upload(name, path))
        }
    }

}